
balance_panel_df = readRDS('data/balance_panel_df.rds')

df <- readRDS('data/full_panel_df.rds') %>% 
  filter(cohort == "2011" | cohort == "2012" | cohort == '2013' | cohort == '10000') %>% 
  filter(year >= 2008) %>% 
  filter(year <= 2014) %>% 
  mutate(
    treat = ifelse(treated_ever==1, as.numeric(year>=cohort, 1,0), 0)
  ) %>% 
  select('DISTID', 'year', 'cohort', 'treat', 
         'aog_no_ied', 'IED_Explosion', 'DF', 'ied', 
         'totalcas', 'treated_ever', 'ipop'
  ) 

df  = df %>% 
  group_by(DISTID) %>% 
  filter(year < 2014) %>% 
  mutate(
    aog_no_ied = log(((aog_no_ied/ipop)*1e5)+1) , 
    ied = log(((ied/ipop)*1e5)+1), 
    IED_Explosion = log(((IED_Explosion/ipop)*1e5)+1), 
    DF = log(((DF/ipop)*1e5)+1), 
    totalcas = log(((totalcas/ipop)*1e5)+1)
    
  ) %>% 
  as.data.frame()



#### Combat #### 
df2 = df %>% 
  dplyr::select('aog_no_ied', 'ied', "DF", 
                "IED_Explosion", 'totalcas',
                'treat', 'DISTID', 'year', 
                'cohort', 'treated_ever')
J <- 5
out_names <- names(df2)[1:J]

att_tjbal <- matrix(, nrow = J, ncol = 3)

df2 = df2 %>% 
  filter(year < 2014) %>% 
  dplyr::select('aog_no_ied', 'ied', "DF", 
                "IED_Explosion", 'totalcas',
                'treat', 'DISTID', 'year', 
                'cohort', 'treated_ever') %>% 
  as.data.frame()

for(j in 1:J){
  
  att_tjbal[j, 1:3] <- print(tjbal(data = df2, Y = out_names[j], D = "treat", 
                                   index = c("DISTID", "year"), 
                                   demean = F, estimator = "mean", 
                                   vce = "jackknife"))[c(1,2,6)]
  
}

make_tjbal_table(att_tjbal, 2, 1, out_names = c('AOG', 'IED', "DF", 
                                                "IED Explosions", 'Causality Events'), 
                 data = df2, id = df2$DISTID, 
                 time = df2$year, treated_group = df2$treated_ever, 
                 outcome_matrix = df2[,1:5], header = FALSE, header_labels = NA, 
                 label_treatment = 'Taliban Courts', extra_arg = c('Dataset', 
                                                                   rep('ANSO', 2), 
                                                                   rep('SIGACT', 3)),
                 file_save = paste0(getwd(), "//tables", "//combat_table_pc_log.tex")
)


